package com.lixh.sdk.base.promision.contract

import android.Manifest
import android.app.Activity
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import androidx.activity.result.contract.ActivityResultContract
import androidx.activity.result.contract.ActivityResultContracts.RequestMultiplePermissions
import androidx.core.app.ActivityCompat

class RequestBlueContract : ActivityResultContract<Unit, Boolean>() {
    var context: Context? = null

    override fun createIntent(context: Context, input: Unit): Intent {
        this.context = context
        //是否打开蓝牙
        return if (!isEnabledBlue(context)) {
            Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE).apply {
                flags = Intent.FLAG_ACTIVITY_NEW_TASK
            }
        } else {
            //需要定位权限才能扫描设备
            Intent(RequestMultiplePermissions.ACTION_REQUEST_PERMISSIONS).putExtra(
                RequestMultiplePermissions.EXTRA_PERMISSIONS,
                arrayOf(Manifest.permission.ACCESS_FINE_LOCATION)
            )
        }
    }

    private fun isEnabledBlue(context: Context) = lazy {
        val mBluetoothAdapter: BluetoothAdapter =
            (context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager).adapter
        (mBluetoothAdapter.isEnabled)
    }.value

    override fun getSynchronousResult(
        context: Context,
        input: Unit
    ): SynchronousResult<Boolean>? {
        if (isEnabledBlue(context) && ActivityCompat.checkSelfPermission(
                context, Manifest.permission.ACCESS_FINE_LOCATION
            ) == PackageManager.PERMISSION_GRANTED
        ) {
            return SynchronousResult(true)
        }
        return null
    }

    override fun parseResult(resultCode: Int, intent: Intent?): Boolean =
        context?.let {
            isEnabledBlue(it) && ActivityCompat.checkSelfPermission(
                it, Manifest.permission.ACCESS_FINE_LOCATION
            ) == PackageManager.PERMISSION_GRANTED
        } ?: false


}